<?php

require_once('config/maptrick.conf.php');
require_once(SITE_ROOT . 'lib/SmartyMaptrick.class.php');
require_once(SITE_ROOT . 'class/logic/Registration.class.php');
require_once(SITE_ROOT . 'class/logic/LogicCoolness.class.php');
require_once(SITE_ROOT . 'class/Exceptions.class.php');
require_once(SITE_ROOT . 'class/bean/Team.class.php');
require_once(SITE_ROOT . 'lib/Session.php');

	//error_reporting(E_ALL);

	$logic = LogicCoolness::getInstance();
	$smarty = new SmartyMaptrick();
	$team = new Team();
	
	if (count($_GET) > 0) {
		if (isset($_GET['team'])) $teamID = $_GET['team'];
	}
	else {
		if (isset($_SESSION['team'])) $teamID = $_SESSION['team'];
		if (isset($_POST['teamID'])) $teamID = $_POST['teamID'];	
	}
	$_SESSION['team'] = $teamID;
	
	$hidden = $_POST['hidden'];
	
	if ($hidden == 'login') {
		try {
			$register = new Registration;
			$register->login($_POST['user'], $_POST['password']);
		}
		catch (Exception $e) {
			$smarty->assign('message', $e->getMessage());
		}
	}
	else if ($hidden == 'logout') {
		try {
			$register = new Registration;
			$register->logout();
		}
		catch (Exception $e) {}
	}
	else if ($hidden == 'updaut') {
		try {
			if (($teamID == 0 && is_numeric($teamID)) || $teamID === "") {
				$teamID = $_SESSION['login_teamID'];
				$_SESSION['team'] = $teamID;
			}			
			if (preg_match("/^[0-9]{1,7}$/", $teamID)) {
				$team = $logic->autoUpdate($teamID, true);
			}
			else $smarty->assign('error', "The TeamID isn't valid! It may only contain numbers.");
		}
		catch (IsBotException $ibe) {
			$smarty->assign('warning', "You don't really want to get the coolness ratings from a bot, do you? If the former owner was in the Hall of Cool he isn't anymore now.");
		}
		catch (LeagueNotAvailableException $lnae) {
			$smarty->assign('warning', "The league the team is playing in couldn't be determinated. It wasn't saved/updated in the Hall of Cool. Please try again later!");
			$team = $lnae->getTeam();
		}
		catch (Exception $e) {
			unset($_SESSION['login']);
			unset($_SESSION['login_teamID']);
			unset($_SESSION['HT']);
			$smarty->assign('message', 'Timeout!');
		}
	}
	else if ($hidden == 'updman') {
		$team = $logic->manUpdate($_POST['away'], $_POST['home'], null, true);
		unset($_SESSION['team']);
		unset($teamID);
	}
	else {
		if (isset($teamID)) {
			if (preg_match("/^[0-9]{1,7}$/", $teamID)) {
				try {
					$team = $logic->dbUpdate($teamID);
				}
				catch (Exception $e) {
					$smarty->assign('error', $e->getMessage());
				} 
			}
			else $smarty->assign('error', "The TeamID isn't valid! It may only contain numbers.");			
		}
		else if ($logic->hasCookieSet() && !isset($_SESSION['result'])) {
			$team = $logic->cookieUpdate();
		}
	}
	
	if (count($team->getFlags()) > 0) {
		$_SESSION['results'] = true;
	}
	else unset($_SESSION['results']);
	
	$smarty->assign('action', $_SERVER['PHP_SELF']);
	$smarty->assign('loggedIn', $_SESSION['login']);

	// assign the important attributes for the header
	$smarty->assign('title', 'Maptrick');
	$smarty->assign('home_active', '');
	$smarty->assign('cool_active', 'active');
	$smarty->assign('hoc_active', '');
	
	$logic = LogicCoolness::getInstance();
	$smarty->assign('introduction', "<p>This ranking shows how hard it is to get a flag of a certain Hattrick country on your club page, by chartering a friendly in that country. The rationale behind the coolness rating is, that it is cool to have a flag that is hard to get! For instance, pretty much anyone who would want to get a Swedish flag could get it, even in the first weeks of the cup; however, it could take the most dedicated flaghunter many seasons to conquer flags from countries like Mongolia, Suriname or Armenia. Because of the low number of active users in those leagues, they are the hardest to get a flag from. This is reflected in the coolness rating; it is calculated as the global number of active users (" . $logic->countUsers() . ") divided by the respective leagues' active users. This means that the less active users a league has, the higher the coolness ratio becomes!</p><p>The 'ND' column shows the minimum number of divisions needed, if no ownerless teams existed in the higher divisions. If the number is higher than the actual number of divisions, then the league is due for expansion; if the number is lower, then it may have been expanded prematurely.</p>");
	
	$smarty->assign_by_ref('coolnessTable', $logic->createCoolnessTable());
	
	if ($teamID != $_SESSION['login_teamID']) {
		$smarty->assign('teamID', $teamID);
	}
	
	if ($_SESSION['results'] === true) {
		$visited = array('coolness' => $team->getAwayCoolness(), 'flags' => $team->getAwayFlags());
		if ($team->getAwayCountry() !== null) {
			$visited['coolestCountry'] = $team->getAwayCountry()->getName();
			$visited['coolest'] = $team->getAwayCountry()->getCoolness();
		}
		$hosted = array('coolness' => $team->getHomeCoolness(), 'flags' => $team->getHomeFlags());
		if ($team->getHomeCountry() !== null) {
			$hosted['coolestCountry'] = $team->getHomeCountry()->getName();
			$hosted['coolest'] = $team->getHomeCountry()->getCoolness();
		}
		$and = array('coolness' => $team->getAndCoolness(), 'flags' => $team->getAndFlags());
		if ($team->getAndCountry() !== null) {
			$and['coolestCountry'] = $team->getAndCountry()->getName();
			$and['coolest'] = $team->getAndCountry()->getCoolness();
		}
		$or = array('coolness' => $team->getOrCoolness(), 'flags' => $team->getOrFlags());
		if ($team->getOrCountry() !== null) {
			$or['coolestCountry'] = $team->getOrCountry()->getName();
			$or['coolest'] = $team->getOrCountry()->getCoolness();
		}
		$plus = array('coolness' => $team->getPlusCoolness(), 'flags' => $team->getPlusFlags());
		if ($team->getPlusCountry() !== null) {
			$plus['coolestCountry'] = $team->getPlusCountry()->getName();
			$plus['coolest'] = $team->getPlusCountry()->getCoolness();
		}
		
		$flags = $logic->countCountries();
		$coolness = $logic->sumCoolness();
		$plus_all_flags = $flags*2;
		$plus_all_coolness = $coolness*2;
		
		$smarty->assign('results', $_SESSION['results']);
		$smarty->assign('teamname', $team->getName());
		$smarty->assign('map_title', 'Map');
		
		$smarty->assign('summary_title', 'Summary');	
		$smarty->assign('flags', $flags);
		$smarty->assign('coolness', $coolness);	
		
		$smarty->assign('away_flags', $visited['flags']);
		$smarty->assign('away_flags_percentage', round(($visited['flags']/$flags)*100, 2));
		$smarty->assign('away_coolness', $visited['coolness']);
		$smarty->assign('away_coolness_percentage', round(($visited['coolness']/$coolness)*100, 2));
		$smarty->assign('away_rarest', $visited['coolestCountry']);
		if ($visited['coolness']) {
			$smarty->assign('away_rarest_percentage', round(($visited['coolest']/$visited['coolness'])*100, 2));
		}
		else $smarty->assign('away_rarest_percentage', 0);
		
		$smarty->assign('home_flags', $hosted['flags']);
		$smarty->assign('home_flags_percentage', round(($hosted['flags']/$flags)*100, 2));
		$smarty->assign('home_coolness', $hosted['coolness']);
		$smarty->assign('home_coolness_percentage', round(($hosted['coolness']/$coolness)*100, 2));
		$smarty->assign('home_rarest', $hosted['coolestCountry']);
		if ($hosted['coolness'] > 0) {
			$smarty->assign('home_rarest_percentage', round(($hosted['coolest']/$hosted['coolness'])*100, 2));
		}
		else $smarty->assign('home_rarest_percentage', 0);
		
		$smarty->assign('and_flags', $and['flags']);
		$smarty->assign('and_flags_percentage', round(($and['flags']/$flags)*100, 2));
		$smarty->assign('and_coolness', $and['coolness']);
		$smarty->assign('and_coolness_percentage', round(($and['coolness']/$coolness)*100, 2));
		$smarty->assign('and_rarest', $and['coolestCountry']);
		if ($and['coolness'] > 0) {
			$smarty->assign('and_rarest_percentage', round(($and['coolest']/$and['coolness'])*100, 2));
		}
		else $smarty->assign('and_rarest_percentage', 0);	
	
		$smarty->assign('or_flags', $or['flags']);
		$smarty->assign('or_flags_percentage', round(($or['flags']/$flags)*100, 2));
		$smarty->assign('or_coolness', $or['coolness']);
		$smarty->assign('or_coolness_percentage', round(($or['coolness']/$coolness)*100, 2));
		$smarty->assign('or_rarest', $or['coolestCountry']);
		if ($or['coolness']) {
			$smarty->assign('or_rarest_percentage', round(($or['coolest']/$or['coolness'])*100, 2));
		}
		else $smarty->assign('or_rarest_percentage', 0);
		
		$smarty->assign('plus_flags', $plus['flags']);
		$smarty->assign('plus_all_flags', $plus_all_flags);
		$smarty->assign('plus_flags_percentage', round(($plus['flags']/$plus_all_flags)*100, 2));
		$smarty->assign('plus_coolness', $plus['coolness']);
		$smarty->assign('plus_all_coolness', $plus_all_coolness);
		$smarty->assign('plus_coolness_percentage', round(($plus['coolness']/$plus_all_coolness)*100, 2));
		$smarty->assign('plus_rarest', $plus['coolestCountry']);
		if ($plus['coolness']) {
			$smarty->assign('plus_rarest_percentage', round(($plus['coolest']/$plus['coolness'])*100, 2));
		}
		else $smarty->assign('plus_rarest_percentage', 0);
	
		$smarty->assign('away_title', 'Away stats');
		$smarty->assign('away_text', 'Coolness score based on countries currently visited: ' . $visited['coolness'] . ' (' . $visited['flags'] . ' countries). The coolest country you have visited is ' . $visited['coolestCountry'] . '.<br />');
		$smarty->assign('home_title', 'Home stats');
		$smarty->assign('home_text', 'Coolness score based on countries currently hosted: ' . $hosted['coolness'] . ' (' . $hosted['flags'] . ' countries). The coolest country you have hosted is ' . $hosted['coolestCountry'] . '.<br />');
		$smarty->assign('combined_title', 'Combined stats');
		$smarty->assign('combined_text', 'Coolness score based on countries currently visited and hosted as well: ' . $and['coolness'] . ' (' . $and['flags'] . ' countries)<br />Coolness score based on countries currently either visited or hosted: ' . $or['coolness'] . ' (' . $or['flags'] . ' countries)<br />Coolness score based on countries currently visited and hosted: ' . $plus['coolness'] . ' (' . $plus['flags'] . ' countries)<br />');
	}
	
	$smarty->assign('explanation', "<p>* This shows the percentage of your collected flags to the total number of flags in the according category. There are " . $flags . " flags in all categories, except for away PLUS home in which you can collect up to " . $plus_all_flags . " flags.<br />** That's the percentage of your achieved score to the reachable score. The highest score in all categories is " . $coolness . ", except for away PLUS home where you can reach " . $plus_all_coolness . " points.<br />*** This shows you how many percent of your total score your coolest country is responsible for.</p>");
	
	$smarty->display('header.tpl');
	$smarty->display('coolness.tpl');
	$smarty->display('footer.tpl');
	
?>